package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.PurchaseOrderMapper;
import com.example.crossborderecommerce.mapper.ReviewMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@Transactional
@RequestMapping("/review")
public class ReviewController {
    @Resource
    IReviewService reviewService;

    @Resource
    ICustomerOrderService customerOrderService;

    @Resource
    IShopService shopService;

    @Resource
    IProductService productService;

    @Resource
    ICustomerService customerService;

    @Resource
    ReviewMapper reviewMapper;

    @Resource
    IStoreCommodityService storeCommodityService;

    /**
     * 添加评价
     * @param review
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Review review){
        CustomerOrder customerOrder = customerOrderService.getById(review.getOrderId());
        Product product = productService.getById(customerOrder.getProductId());
        Integer grade = review.getGrade();
        product.setScore((product.getScore() * product.getReviewTimes() + grade) / (product.getReviewTimes() + 1));
        product.setReviewTimes(product.getReviewTimes() + 1);
        productService.save(product);
        boolean res = reviewService.save(review);
        if(res){
            return Result.success("添加评价成功！");
        }
        return Result.error("添加评价失败！");
    }

    /**
     * 删除评价
     * @param review
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Review review){
        CustomerOrder customerOrder = customerOrderService.getById(review.getOrderId());
        Product product = productService.getById(customerOrder.getProductId());
        Integer grade = review.getGrade();
        product.setScore((product.getScore() * product.getReviewTimes() - grade) / (product.getReviewTimes() - 1));
        product.setReviewTimes(product.getReviewTimes() - 1);
        productService.save(product);

        boolean res = reviewService.removeById(review);
        if(res){
            return Result.success("删除评价成功！");
        }
        return Result.error("删除评价失败！");
    }

    /**
     * 删除一系列评价
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> reviewIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        for(String reviewId : reviewIds) {
            Review review = reviewService.getById(reviewId);
            CustomerOrder customerOrder = customerOrderService.getById(review.getOrderId());
            Product product = productService.getById(customerOrder.getProductId());
            Integer grade = review.getGrade();
            product.setScore((product.getScore() * product.getReviewTimes() - grade) / (product.getReviewTimes() - 1));
            product.setReviewTimes(product.getReviewTimes() - 1);
            productService.save(product);
        }
        boolean res = reviewService.removeByIds(reviewIds);
        if(res) {
            return Result.success("删除评价成功");
        }
        return Result.error("删除评价失败！");
    }

    /**
     * 查找所有评价
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Review> reviewList = reviewService.list();
        if(reviewList == null) {
            return Result.error("获取全部评价失败！");
        }
        for(Review review : reviewList) {
            if(review.getOrderId() != null) {
                CustomerOrder customerOrder = customerOrderService.getById(review.getOrderId());
                Product product = productService.getById(customerOrder.getProductId());
                Shop shop = shopService.getById(customerOrder.getShopId());
                Customer customer = customerService.getById(customerOrder.getCustomerId());
                review.setProduct(product);
                review.setShopName(shop.getName());
                review.setCustomerName(customer.getName());
            }
        }
        return Result.success("获取全部评价成功！", reviewList);
    }

    /**
     * 根据产品id获取评价
     * @param productId
     * @return
     */
    @GetMapping("/findReviewsByProductId")
    public Result findReviewsByProductId(@RequestParam("productId") String productId) {
        List<Review> reviewList = reviewMapper.finReviewsByOrderId(productId);
        if(reviewList == null) {
            return Result.error("获取评价失败！");
        }
        for(Review review : reviewList) {
            if(review.getOrderId() != null) {
                CustomerOrder customerOrder = customerOrderService.getById(review.getOrderId());
                Product product = productService.getById(customerOrder.getProductId());
                Shop shop = shopService.getById(customerOrder.getShopId());
                Customer customer = customerService.getById(customerOrder.getCustomerId());
                review.setProduct(product);
                review.setShopName(shop.getName());
                review.setCustomerName(customer.getName());
            }
        }
        return Result.success("获取全部评价成功！", reviewList);
    }

    /**
     * 修改评价
     * @param review
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Review review) {
        boolean res = reviewService.saveOrUpdate(review);
        if (res) {
            return Result.success("修改评价成功！");
        }
        return Result.error("修改评价失败！");
    }

    /**
     * 分页获取全部评价
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String type) {
        Page<Review> reviewPage = new Page<>(pageNum, pageSize);
        List<Review> reviewList = reviewMapper.getReviewByPage(reviewPage,type);
        for(Review review : reviewList) {
            if(review.getOrderId() !=null){
                CustomerOrder customerOrder = customerOrderService.getById(review.getOrderId());
                StoreCommodity storeCommodity = storeCommodityService.getById(customerOrder.getStoreCommodityId());
                Product product = productService.getById(storeCommodity.getProductId());
                Shop shop = shopService.getById(customerOrder.getShopId());
                Customer customer = customerService.getById(customerOrder.getCustomerId());
                review.setProduct(product);
                review.setShopName(shop.getName());
                review.setCustomerName(customer.getName());
            }
        }
        Page<Review> newReviewPage = new Page<>(pageNum, pageSize);
        newReviewPage.setRecords(reviewList);
        newReviewPage.setTotal(reviewPage.getTotal());
        return Result.success("成功查询所有评价！",newReviewPage);
    }

    /**
     * 获取评价总数
     * @return
     */
    @GetMapping("/count")
    public Result count() {
        return Result.success(reviewService.count());
    }

    /**
     * 获取今日评价数
     * @return
     */
    @GetMapping("/countToday")
    public Result countToday() {
        LocalDate today = LocalDate.now();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startOfDay = LocalDateTime.of(today, LocalTime.MIDNIGHT);
        LocalDateTime endOfDay = LocalDateTime.of(today, LocalTime.of(23, 59, 59));
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        String formattedStartDate = sdf.format(startDate);
        String formattedEndDate = sdf.format(endDate);
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("create_time", formattedStartDate, formattedEndDate);
        return Result.success(reviewService.count(queryWrapper));
    }

    /**
     * 获取星级为1-3星的评价数
     * @return
     */
    @GetMapping("/countOneToThree")
    public Result countOneToThree() {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("grade", 1, 3);
        return Result.success(reviewService.count(queryWrapper));
    }

    /**
     * 获取星级为4-5星的评价数
     * @return
     */
    @GetMapping("/countFourToFive")
    public Result countFourToFive() {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("grade", 4, 5);
        return Result.success(reviewService.count(queryWrapper));
    }
}
